package org.dant.ant.extension.types;

import java.io.*;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.types.DataType;

public class Expect extends DataType implements Serializable {

    protected boolean errstream;
    protected boolean empty;
    protected boolean exact;
    protected boolean negativematch;
    protected boolean erroronfail;

    protected File file;
    protected File dir;
    protected String text;
  
    public void setStream(String stream) {
        if ("err".equalsIgnoreCase(stream)) {
            errstream = true;
        } else if ("out".equalsIgnoreCase(stream)) {
            errstream = false;
        } else {
            throw new BuildException("Invalid Streamtype: only \"out\" and \"err\" allowed!");
        }
    }

    public void setEmpty(boolean e) {
        this.empty = e;
    }

    public void setFile(String f) {
        if (f == null) {
            return;
        }
        if (dir == null) {
            file = new File(f);
        } else {
            file = concatFiles(dir, f);
        }
        //     if (f.equals("core")) {
        //       saveExistingFile(file);
        //     } else {
        //       deleteExistingFile(file);
        //     }
    }

    public void setDir(File d) {
        if (d == null) {
            return;
        }
        dir = d;
        if (file != null) {
            file = concatFiles(dir, file.toString());
      
            //       if (file.getName().equals("core")) {
            //         saveExistingFile(file);
            //       } else {
            //         deleteExistingFile(file);
            //       }
        }
    }
  
    public void addText(String txt) {
        text = getProject().replaceProperties(txt);
    }
  
    public boolean isErrStream() {
        return this.errstream;
    }

    public File getFile() {
        return this.file;
    }

    public String getText() {
        return this.text;
    }

    //   public String getOutStream() {
    //     return stdout.toString();
    //   }

    //   public String getErrStream() {
    //     return stderr.toString();
    //   }

    protected static File concatFiles(File dir, String filename) {
        try {
            return new File(dir, filename).getCanonicalFile();
        } catch (IOException ioe) {
            return new File(dir, filename).getAbsoluteFile();
        }
    }

    public String toString() {
        StringBuffer sb = new StringBuffer();
        if (getFile() == null) {
            sb.append("expect ");
            if (errstream) {
                sb.append(" stderr ");
            } else {
                sb.append(" stdout ");
            }
                
            sb.append("stream: ");
            sb.append(getText());
            sb.append("\n");
        } else {
            sb.append("expect file: ");
            sb.append(getFile().toString());
        }
        return sb.toString();
    }
}
